from rest_framework.decorators import action
from django.shortcuts import render
from django.views import View
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.db.models import F
from rest_framework.viewsets import ReadOnlyModelViewSet, ModelViewSet

from community.models import Label, Article, Comment
from community.serializers import LabelSerializer, ArticleSerializer,CommentSerializer,SonCommentSerializer
from .paginations import ArticlePageNumberPagination,ArticleLimitOffsetPagination

# Create your views here.

# 标签不需要增删改的接口
# 只需要查询接口


class LabelViewSet(ReadOnlyModelViewSet):
    # 查询操作
    queryset = Label.objects.all()
    serializer_class = LabelSerializer
    # 标签只有登录才能看到
    permission_classes = [IsAuthenticated]

# 文章的增删改查
class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.filter(is_delete=False)
    serializer_class = ArticleSerializer
    permission_classes = [IsAuthenticated]

    # 分页器
    pagination_class = ArticleLimitOffsetPagination


    # #重写查询集
    # def get_queryset(self):
    #     #查看的文章 发布的文章才可以查看
    #     if self.action in ['list', 'retrieve']:
    #         return self.queryset.filter(status=1)
    #     else:
    #         return self.queryset

    #重写序列化器
    def get_serializer_class(self):
        if self.action == "comment":
            return CommentSerializer
        else:
            return ArticleSerializer

    # create方法重写一下
    def create(self, request, *args, **kwargs):
        request.POST._mutable = True # 允许修改post传入的参数  1     2
        request.data["user"] = request.user.id
        # 因为重写create方法 还需要用到 create的功能
        return ModelViewSet.create(self, request, *args, **kwargs)

    #浏览量
    def retrieve(self, request, *args, **kwargs):
        self.get_queryset().filter(id=kwargs['pk']).update(page_view=F('page_view') + 1)
        return ModelViewSet.retrieve(self, request, *args, **kwargs)

    # 获取当前文章的所有一级评论  detail=True 要传id
    @action(detail=True, methods=['get'])
    def comment(self,request, pk=None):
        try:
            article = self.get_queryset().get(id=pk)
        except Article.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        #根据文章 进行关联查询  得到一级评论
        comments = article.comment_set.filter(parent_comment__isnull=True)
        #添加分页器
        comments = self.paginate_queryset(comments)
        # 序列化 评论的序列化
        serializer = self.get_serializer(comments, many=True)
        # return Response(serializer.data)
        return self.get_paginated_response(serializer.data)



class CommentViewSet(ModelViewSet):
    queryset = Comment.objects.filter(is_delete=False,article__is_delete=False,article__status=1)
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = ArticleLimitOffsetPagination

    def create(self, request, *args, **kwargs):
        request.POST._mutable = True  # 允许修改post传入的参数  1     2
        request.data["user"] = request.user.id
        # 因为重写create方法 还需要用到 create的功能
        return ModelViewSet.create(self, request, *args, **kwargs)

    def get_serializer_class(self):
        if self.action == "retrieve":
            return SonCommentSerializer
        else:
            return CommentSerializer

    #展示当前父级评论下的子集评论
    def retrieve(self, request, *args, **kwargs):
        try:
            comment = self.get_queryset().get(id=kwargs['pk'])
        except Comment.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        #有一级评论 反向查询
        comments = comment.parent_comment_set.all()
        comments = self.paginate_queryset(comments)
        serializer = self.get_serializer(comments, many=True)
        # return Response(serializer.data)
        return self.get_paginated_response(serializer.data)